<?php
/**
 * Created by PhpStorm.
 * User: leo
 * Date: 16/4/6
 * Time: 下午5:30
 * Describe:
 */

namespace services\sms;


/**
 * Class LianWSms
 * 北京联合维拓科技有限公司
 * 网址：www.univetro.cn
 * 传真：010-65830031
 * 地址： 北京市朝阳区光华路甲8号和乔大厦A座325室（100026）
 */
class LianWSms extends SmsBase
{
    private $preSign='【有试吗】';
    public $cdkey ;
    public $password ;

    public function __construct()
    {
        parent::__construct();
        $this->url = "http://sdk.univetro.com.cn:6200/sdkproxy/%s.action";
    }

    protected function getDataStruct($cell='', $content='', $sendTime = '')
    {

        $data = array(
            'cdkey' => $this->cdkey,
            'password' => $this->password,
        );

        return $data;
    }

    /**
     * @param array|string $cell
     * @param string $content
     * @param int $uid
     * @param int $department
     * @param string $sendTime
     * @return mixed
     *
     * $taskId 自己生成
     */
    public function setSingleMsm($cell, $content, $uid = 0, $department = 12, $sendTime = '')
    {
        $check_flag = $this->cellCheck($cell, $content);

        if ($check_flag == true) {
            $this->saveErrorMsg('setSingleMsm', $content, '频繁发送', $cell);
            return false;
        }

        $taskId = $this->taskId;

        $url = sprintf($this->url, "sendsms");
        if ($sendTime != '') {
            $url = sprintf($this->url, "sendtimesms");
        }
        $post_data = $this->getDataStruct($cell, $content, $sendTime);
        $post_data['seqid'] = $taskId;
        $post_data['phone'] = $cell;

        /**
         * 从sendBatchMessage方法中的调用, 已经添加了前缀
         * 在此判断下内容中是否有前缀, 如果没有, 则加上.
         */
        if(strpos($content, $this->preSign)!==0){
            $content = $this->preSign.$content;
        }

        $post_data['message'] = $content;
        $result = $this->curl($url, $post_data);
        $resultArr = $this->parseResult($result);

        if (isset($resultArr['error']) && $resultArr['error'] == '0') {

            $this->saveData($taskId, $cell, $content, $uid, $department, $sendTime);

        } else {
            $this->saveErrorMsg('setSingleMsm', $post_data, $result, $cell);
        }
        return $result;

    }

    /**
     *
     * 上行
     * <?xml version="1.0" encoding="UTF-8"?>
     * <response>
     * <error>0</error>
     * <message>
     * <srctermid>18602112511</srctermid>
     * <sendTime>20151127152903</sendTime>
     * <msgcontent>该项</msgcontent>
     * <addSerial></addSerial>
     * <addSerialRev>523492</addSerialRev>
     * </message>
     * <message>
     * <srctermid>18602112511</srctermid>
     * <sendTime>20151127152903</sendTime>
     * <msgcontent>不想做梦梦见和小姐妹的</msgcontent>
     * <addSerial></addSerial>
     * <addSerialRev>523492</addSerialRev>
     * </message>
     * </response>
     */
    public function getReceivedMsg()
    {
        $url = sprintf($this->url, "getmo");
        $post_data = $this->getDataStruct();

        $result = $this->curl($url, $post_data);
        $resultArr = $this->parseResult($result);

        foreach ($resultArr['message'] as $message) {
            $cell = strlen($message['srctermid']) >11?substr($message['srctermid'],-11):$message['srctermid'];

            //$taskId, $cell, $content, $receiveTime
            $this->saveReceived(
                $message['addSerialRev'],
                $cell,
                $message['msgcontent'],
                preg_replace('/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/', '$1-$2-$3 $4:$5:$6', $message['sendTime'])
            );

        }
        return count($resultArr['message']);


    }

    public function getUserInfo()
    {
        $url = sprintf($this->url, "querybalance");
        $post_data = $this->getDataStruct();

        $result = $this->curl($url, $post_data);
        $resultArr = $this->parseResult($result);

        return (int)($resultArr['message'] * 10);
    }

    protected function parseResult($context)
    {
        $context = str_replace("\r\n", "", $context);

        if (!$dom = simplexml_load_string($context)) {
            return false;
        }
        return json_decode(json_encode($dom), true);
    }

    /**
     *状态
     * <?xml version="1.0" encoding="UTF-8"?>
     * <response>
     * <error>0</error>
     * <message>
     * <srctermid>8618602112511</srctermid>
     * <submitDate>20151127152535</submitDate>
     * <receiveDate>20151127152535</receiveDate>
     * <addSerial></addSerial>
     * <addSerialRev></addSerialRev>
     * <state>DELIVRD</state>
     * <seqid>7</seqid>
     * </message>
     * <message>
     * <srctermid>8618602112511</srctermid>
     * <submitDate>20151127152104</submitDate>
     * <receiveDate>20151127152104</receiveDate>
     * <addSerial></addSerial>
     * <addSerialRev></addSerialRev>
     * <state>DELIVRD</state>
     * <seqid>6</seqid>
     * </message>
     * </response>
     */
    public function getSmsStatus()
    {
        $url = sprintf($this->url, "getreport");
        $post_data = $this->getDataStruct();

        $result = $this->curl($url, $post_data);
        $resultArr = $this->parseResult($result);

        foreach ($resultArr['message'] as $message) {
            //$task_id, $cell, $status, $time
            $cell = strlen($message['srctermid']) >11?substr($message['srctermid'],-11):$message['srctermid'];
            $this->updateStatus($message['seqid'],
                $cell,
                $message['state'],
                preg_replace('/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/', '$1-$2-$3 $4:$5:$6', $message['receiveDate']));
        };
        return count($resultArr['message']);
    }

    public function  __get($propertyName){

        if($propertyName == 'taskId'){
            return $this->getTaskId();
        }
        if(isset($this->$propertyName)){
            return $this->$propertyName;
        }else{
            return null;
        }
    }
    /**
     * 生成taskId
     *
     * @return int
     *
     * 联合维拓 短信taskId需要自己提供
     */
    private function getTaskId()
    {
        $serialNo = \Yii::$app->redis->incr(\Yii::$app->params['LianWSms']);
        return is_integer($serialNo) ? $serialNo : 0;
    }

}